package com.bmw.redis3.util;



import com.bmw.redis3.base.Constant;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Classname: DecrCacheStockUtil
 * Package: com.bmw.seckill.commom.util
 * Description:
 *
 * @Author 王少伟
 * @Create 2024/4/13 20:13
 * @Version 1.8
 */
@Component
@Slf4j
public class DecrCacheStockUtil {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private DefaultRedisScript<Long> getRedisScript;

    private String subStock = "local key=KEYS[1];\n"+
            "local surplusStock = tonumber(redis.call('get',key));\n"+
            "if (surplusStock<=0) then return 0\n"+
            "else\n"+
            "   redis.call('incrby',key,-1)\n"+
            "   return 2 \n"+
            "end";

    //Constructor>>@Autowired>>@PostConstruct
    //@PostConstruct注解的方法在项目启动的时候执行这个方法，也可以理解为在spring容器启动的时候执行，可以作为一些数据的常规化加载，
    //比如数据字典之类的

    @PostConstruct
    public void init(){
        getRedisScript = new DefaultRedisScript<Long>();
        getRedisScript.setResultType(Long.class);
        getRedisScript.setScriptText(subStock);
    }

    /**
     * 浏览量-1
     * @param messageId
     * @return
     */
    public Long decrStock(Long messageId){
        Long res = redisTemplate.execute(getRedisScript, Lists.newArrayList(String.format(Constant.redisKey.Message_VISITS,messageId)));
        return res;
    }

    /**
     * 浏览量加+1
     * @param messageId
     */

    public void addStock(Long messageId){
        String key = String.format(Constant.redisKey.Message_VISITS,messageId);
        if(redisTemplate.hasKey(key)){
            redisTemplate.opsForValue().increment(key);
        }
    }

}
